package com.prawn.user.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import util.IdWorker;

import com.prawn.user.dao.AdminDao;
import com.prawn.user.pojo.Admin;
import util.NullAttributeUtils;

/**
 * 服务层
 * 
 * @author Administrator
 *
 */
@Service
public class AdminService {

	@Autowired
	private AdminDao adminDao;
	
	@Autowired
	private IdWorker idWorker;

	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;

	/**
	 * 登录验证
	 * @param admin
	 * @return Admin
	 */
	public Admin login(Admin admin) {
		Admin adminLogin = adminDao.findByLoginName(admin.getLoginName());
		//验证登录密码
		if (adminLogin != null && bCryptPasswordEncoder.matches(admin.getPassword(),adminLogin.getPassword())) {
			return adminLogin;
		}
		return null;
	}

	/**
	 * 查询全部列表
	 * @return
	 */
	public List<Admin> findAll() {
		return adminDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<Admin> findSearch(Map whereMap, int page, int size) {
		Specification<Admin> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return adminDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<Admin> findSearch(Map whereMap) {
		Specification<Admin> specification = createSpecification(whereMap);
		return adminDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	@Cacheable(value = "admin",key = "#id")
	public Admin findById(String id) {
		return adminDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param admin
	 */
	public void add(Admin admin) {
		admin.setId( idWorker.nextId()+"" );
		//密码加密
		admin.setPassword(bCryptPasswordEncoder.encode(admin.getPassword()));
		adminDao.save(admin);
	}

	/**
	 * 修改
	 * @param admin
	 */
	@CacheEvict(value = "admin",key = "#admin.id")
	public void update(Admin admin) {
		//密码加密
		admin.setPassword(bCryptPasswordEncoder.encode(admin.getPassword()));
		adminDao.save(admin);
	}

	/**
	 * 删除
	 * @param id
	 */
	@CacheEvict(value = "admin",key = "#id")
	public void deleteById(String id) {
		adminDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<Admin> createSpecification(Map searchMap) {

		return new Specification<Admin>() {

			@Override
			public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // 归属机构
                if (searchMap.get("companyId")!=null && !"".equals(searchMap.get("companyId"))) {
                	predicateList.add(cb.equal(root.get("companyId").as(String.class), (String)searchMap.get("companyId")));
                }
                // 归属部门
                if (searchMap.get("officeId")!=null && !"".equals(searchMap.get("officeId"))) {
                	predicateList.add(cb.equal(root.get("officeId").as(String.class), (String)searchMap.get("officeId")));
                }
                // 登录名
                if (searchMap.get("loginName")!=null && !"".equals(searchMap.get("loginName"))) {
                	predicateList.add(cb.equal(root.get("loginName").as(String.class), (String)searchMap.get("loginName")));
                }
                // 工号
                if (searchMap.get("no")!=null && !"".equals(searchMap.get("no"))) {
                	predicateList.add(cb.equal(root.get("no").as(String.class), (String)searchMap.get("no")));
                }
                // 姓名
                if (searchMap.get("realname")!=null && !"".equals(searchMap.get("realname"))) {
                	predicateList.add(cb.like(root.get("realname").as(String.class), "%"+(String)searchMap.get("realname")+"%"));
                }
                // 邮箱
                if (searchMap.get("email")!=null && !"".equals(searchMap.get("email"))) {
                	predicateList.add(cb.equal(root.get("email").as(String.class), "%"+(String)searchMap.get("email")+"%"));
                }
                // 电话
                if (searchMap.get("phone")!=null && !"".equals(searchMap.get("phone"))) {
                	predicateList.add(cb.equal(root.get("phone").as(String.class), (String)searchMap.get("phone")));
                }
                // 手机
                if (searchMap.get("mobile")!=null && !"".equals(searchMap.get("mobile"))) {
                	predicateList.add(cb.equal(root.get("mobile").as(String.class), "%"+(String)searchMap.get("mobile")+"%"));
                }
                // 学历
                if (searchMap.get("eduLeve")!=null && !"".equals(searchMap.get("eduLeve"))) {
                	predicateList.add(cb.equal(root.get("eduLeve").as(String.class), (String)searchMap.get("eduLeve")));
                }
                // 性别
                if (searchMap.get("sex")!=null && !"".equals(searchMap.get("sex"))) {
                	predicateList.add(cb.equal(root.get("sex").as(String.class), (String)searchMap.get("sex")));
                }
                // 工作职位
                if (searchMap.get("job")!=null && !"".equals(searchMap.get("job"))) {
                	predicateList.add(cb.equal(root.get("job").as(String.class), (String)searchMap.get("job")));
                }
                // 用户标签信息（预留字段）
                if (searchMap.get("tagInfo")!=null && !"".equals(searchMap.get("tagInfo"))) {
                	predicateList.add(cb.like(root.get("tagInfo").as(String.class), "%"+(String)searchMap.get("tagInfo")+"%"));
                }
                // 用户类型（引用数据字典）
                if (searchMap.get("userType")!=null && !"".equals(searchMap.get("userType"))) {
                	predicateList.add(cb.equal(root.get("userType").as(String.class), (String)searchMap.get("userType")));
                }
                // 最后登陆IP
                if (searchMap.get("loginIp")!=null && !"".equals(searchMap.get("loginIp"))) {
                	predicateList.add(cb.equal(root.get("loginIp").as(String.class), (String)searchMap.get("loginIp")));
                }
                // 用户状态，是否可登录(0:正常
                if (searchMap.get("loginFlag")!=null && !"".equals(searchMap.get("loginFlag"))) {
                	predicateList.add(cb.equal(root.get("loginFlag").as(String.class), "%"+(String)searchMap.get("loginFlag")+"%"));
                }
                // 创建者
                if (searchMap.get("createBy")!=null && !"".equals(searchMap.get("createBy"))) {
                	predicateList.add(cb.equal(root.get("createBy").as(String.class), (String)searchMap.get("createBy")));
                }
                // 更新者
                if (searchMap.get("updateBy")!=null && !"".equals(searchMap.get("updateBy"))) {
                	predicateList.add(cb.equal(root.get("updateBy").as(String.class), (String)searchMap.get("updateBy")));
                }
                // 删除标记（虚拟删除，并不删除数据库表数据，0：正常，1：删除）
                if (searchMap.get("delFlag")!=null && !"".equals(searchMap.get("delFlag"))) {
                	predicateList.add(cb.equal(root.get("delFlag").as(String.class), (String)searchMap.get("delFlag")));
                }
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}

}
